package com.hardy.leetcode;

import java.util.ArrayList;

/**
 * User: Ruijie Date: 2016/8/25
 */
public class SumRootLeaf {

    public static class TreeNode {

        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int value) {
            this.val = value;
        }
    }


    public static int sumNumbers(TreeNode root) {
        ArrayList<Integer> array = new ArrayList<Integer>();
        int[] result = new int[1];
        sum(root, array, result);
        return result[0];
    }

    public static void sum(TreeNode root, ArrayList<Integer> array, int[] sum) {
        if (root != null) {
            array.add(root.val);
            if (root.left == null && root.right == null) {
                int result = 0;
                for (Integer val : array) {
                    result = result * 10 + val;
                }
                System.out.println(result + "       result");
                sum[0] += result;
            } else {
                sum(root.left, array, sum);
                sum(root.right, array, sum);
            }
            array.remove(array.size() - 1);
        }
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.left.left = new TreeNode(3);
        node.left.right = new TreeNode(4);
        node.right = new TreeNode(5);
        node.right.left = new TreeNode(6);
        node.right.right = new TreeNode(7);
        TreeNode leftNode = new TreeNode(1);
        leftNode.left = new TreeNode(3);
        TreeNode rightNode = new TreeNode(1);
        rightNode.right = new TreeNode(5);
        TreeNode LR = new TreeNode(4);
        LR.left = new TreeNode(9);
        LR.left.right = new TreeNode(0);
        LR.right = new TreeNode(1);
        //System.out.println(sumNumbers(node));
        System.out.println();
        //System.out.println(sumNumbers(leftNode));
        System.out.println();
        //System.out.println(sumNumbers(rightNode));
        System.out.println();
        System.out.println(sumNumbers(LR));
    }

}
